/**
 * 购物车模块
 */
(function(window) {
    'use strict';
    
    // 购物车数据
    let cart = [];
    let totalPrice = 0;
    
    // 暴露到全局
    window.cart = cart;
    window.totalPrice = totalPrice;
    
    /**
     * 添加商品到购物车
     */
    function addProductToCart(product) {
        const existingItem = cart.find(item => String(item.barcode) === String(product.barcode));
        
        if (existingItem) {
            existingItem.quantity += 1;
            existingItem.unitPrice = parseFloat(product.price) || 0;
            existingItem.price = existingItem.unitPrice * existingItem.quantity;
        } else {
            cart.push({
                barcode: product.barcode,
                name: product.name,
                unitPrice: parseFloat(product.price) || 0,
                unit: product.unit || '个',
                quantity: 1,
                price: parseFloat(product.price) || 0
            });
        }
    }
    
    /**
     * 更新购物车中的商品
     */
    function updateCartItem(barcode, quantity, price) {
        const item = cart.find(item => String(item.barcode) === String(barcode));
        
        if (item) {
            item.quantity = quantity;
            item.unitPrice = price;
            item.price = quantity * price;
            updateTotalPrice();
        }
    }
    
    /**
     * 从购物车删除商品
     */
    function removeProductFromCart(barcode) {
        const stringBarcode = String(barcode);
        $(`#productList tbody tr[data-id="${stringBarcode}"]`).remove();
        
        const item = cart.find(item => String(item.barcode) === String(barcode));
        if (item) {
            const itemTotal = item.price;
            cart = cart.filter(item => String(item.barcode) !== String(barcode));
            totalPrice -= itemTotal;
            if (totalPrice < 0) totalPrice = 0;
            $('#totalPrice').text(totalPrice.toFixed(2));
        }
    }
    
    /**
     * 清空购物车
     */
    function clearCart() {
        cart = [];
        totalPrice = 0;
    }
    
    /**
     * 更新总价
     */
    function updateTotalPrice() {
        const currentLang = window.currentLang || 'zh';
        const trans = window.translations?.[currentLang];
        
        totalPrice = cart.reduce((sum, item) => {
            const itemPrice = parseFloat(item.price) || 0;
            return sum + itemPrice;
        }, 0);
        
        const totalText = $('#totalPrice').parent();
        totalText.html(`${trans?.total || '合计'} <span id="totalPrice">${totalPrice.toFixed(2)}</span>${trans?.yuan || '元'}`);
    }
    
    // 暴露API
    window.CartModule = {
        addProductToCart: addProductToCart,
        updateCartItem: updateCartItem,
        removeProductFromCart: removeProductFromCart,
        clearCart: clearCart,
        updateTotalPrice: updateTotalPrice,
        getCart: () => cart,
        getTotalPrice: () => totalPrice
    };
    
    // 兼容旧代码
    window.removeProductFromCart = removeProductFromCart;
    
})(window);

